package word

import (
	"fmt"
	"net/http"
	"strings"
	"tushare/model"

	"github.com/PuerkitoBio/goquery"
)

type Spider struct{}

func (s Spider) Koolearn(letter string, page int64) {
	var i int64
	for i = 1; i <= page; i++ {
		fmt.Println(i)
		url := fmt.Sprintf("https://www.koolearn.com/dict/zimu_%s_%d.html", letter, i)
		s.spiderKoolearn(url)
	}

}

//http://www.icooc.com/service/njdpcd/
//http://word.qsbdc.com/wl.php?level=1&&tag=all&&page_id=2
//https://www.hujiang.com/ciku/zuixinyingyusijicihui_228/
func (s Spider) spiderKoolearn(url string) {
	res, err := http.Get(url)
	if err != nil {
		fmt.Println(err)
	}
	defer res.Body.Close()

	if res.StatusCode != 200 {
		fmt.Println("网络未正常响应httpCode:")
		fmt.Println(res.StatusCode)
	}

	doc, err := goquery.NewDocumentFromReader(res.Body)

	if err != nil {
		fmt.Println(err)
	}

	//现价
	doc.Find(".word-box .word").Each(func(i int, s *goquery.Selection) {
		text := s.Text()
		w := model.Word{}
		wInfo := model.WordInfoByName(text)
		if wInfo.Id == 0 {
			w.Name = text
			model.WordCreate(w)
		}
	})
}

//http://www.icooc.com/service/njdpcd/
func (s Spider) LevelFour(url string) {
	res, err := http.Get(url)
	if err != nil {
		fmt.Println(err)
	}
	defer res.Body.Close()

	if res.StatusCode != 200 {
		fmt.Println("网络未正常响应httpCode:")
		fmt.Println(res.StatusCode)
	}

	doc, err := goquery.NewDocumentFromReader(res.Body)

	if err != nil {
		fmt.Println(err)
	}

	doc.Find(".word_main_list .word_main_list_w span").Each(func(i int, s *goquery.Selection) {
		text := s.Text()
		text = strings.TrimSpace(text)
		text = strings.TrimRight(text, "...")

		w := model.Word{}
		wInfo := model.WordInfoByName(text)
		fmt.Println(wInfo)
		if wInfo.Id != 0 {
			w.LevelGre = 1
			model.WordUpdate(wInfo.Id, w)
		} else {
			w.Name = text
			w.LevelGre = 1
			model.WordCreate(w)
		}
	})
}

func (s Spider) ErrorTypo() {
	w := model.WordList(1, 130444)
	for _, v := range w {
		url := fmt.Sprintf("https://www.youdao.com/w/%s/#keyfrom=dict2.top", v.Name)
		res, err := http.Get(url)
		if err != nil {
			fmt.Println(err)
		}
		defer res.Body.Close()

		if res.StatusCode != 200 {
			fmt.Println("网络未正常响应httpCode:")
			fmt.Println(res.StatusCode)
		}

		doc, err := goquery.NewDocumentFromReader(res.Body)

		if err != nil {
			fmt.Println(err)
		}

		//现价
		doc.Find(".error-typo h4").Each(func(i int, s *goquery.Selection) {
			text := s.Text()
			text = strings.TrimSpace(text)
			if text == "您要找的是不是:" {
				fmt.Println(v.Name)
				model.WordDelById(v.Id)
			}
		})
	}
}
